package com.atguigu.gmall.order.handler.impl;

import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.feign.ware.WareFeignClient;
import com.atguigu.gmall.order.handler.AbstractOrderHandler;
import com.atguigu.gmall.order.dto.DetailDto;
import com.atguigu.gmall.order.dto.OrderSubmitDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class WareValidOrderHandler extends AbstractOrderHandler {

    @Autowired
    private WareFeignClient wareFeignClient ;

    @Override
    public int sort() {
        return 3;
    }

    @Override
    public String process(OrderSubmitDto orderSubmitDto, String tradeNo) {

        // 获取明细数据
        List<DetailDto> orderDetailList = orderSubmitDto.getOrderDetailList();

        // 对集合进行遍历
        long count = orderDetailList.stream().filter(detailDto -> {
            Long skuId = detailDto.getSkuId();
            Integer skuNum = detailDto.getSkuNum();
            String hasStock = wareFeignClient.hasStock(skuId, skuNum);      // 0表示无货，1表示有货
            return "0".equals(hasStock);
        }).count();
        if(count > 0) {     // 存在无货的商品
            throw new GmallException(ResultCodeEnum.SKU_HAS_STOCK_ERROR) ;
        }

        // 获取下一个节点，执行下一个操作
        AbstractOrderHandler abstractOrderHandler = this.getNext();
        if(abstractOrderHandler != null) {
            return abstractOrderHandler.process(orderSubmitDto , tradeNo) ;
        }

        return null;
    }
}
